package com.crayon2f.test;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.checkerframework.checker.units.qual.A;
import org.junit.Test;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;

import static java.util.concurrent.TimeUnit.SECONDS;
import static org.awaitility.Awaitility.await;

/**
 * Created by feifan.gou@gmail.com on 2024/7/2 15:37.
 */
public class TEST2024_08 {


    @Test
    public void test() {

//        TreeMap<Long, String> map = new TreeMap<>();
//        map.put(4L, "4");
//        map.put(2L, "4");
//        map.put(5L, "4");
//        System.out.println(map.firstKey());
        Map<String, Object> map = new HashMap<>();
        map.put("3", null);
        System.out.println(map.getOrDefault("3", 4));

    }

    @Test
    public void retry() {

        AtomicInteger attempts = new AtomicInteger(0);

        await()
                .atMost(100, SECONDS) // 最长等待时间
                .pollInterval(2, SECONDS) // 每2秒重试一次
                .until(() -> {
                    attempts.incrementAndGet();
                    return performTask();
                });

        System.out.println("重试次数: " + attempts.get());
    }

    public boolean performTask() {
        // 模拟任务，假设前几次失败，之后成功
        int randomValue = (int) (Math.random() * 10);
        System.out.println("执行任务，随机值: " + randomValue);
        return randomValue > 7; // 条件：随机值大于7时任务成功
    }

    ExecutorService executorService = Executors.newFixedThreadPool(20);

    @Test
    public void testRestart() {

        AtomicBoolean b = new AtomicBoolean(false);

        // 配置请求超时时间
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(10000) // 连接超时：5秒
                .setSocketTimeout(10000) // 请求超时：10秒
                .setConnectionRequestTimeout(8000) // 连接请求超时：5秒
                .build();
        CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
        LongAdder adder = new LongAdder();
        for (int i = 0; i < 20; i++) {
            executorService.submit(() -> {
                await().atMost(Duration.ofHours(2))
                        .pollInterval(Duration.ofSeconds(1))
                        .until(() -> {
                            adder.increment();
                            if (adder.intValue() % 100 == 0) {
                                System.out.println("+++++++++++++++++++ " + adder.intValue() + " +++++++++++++++++++");
                            }
                            HttpGet get = new HttpGet("http://cim-base-zuul.test.fnwintranet.com/cim/api-service/queryLargeDeviceType");
                            try {
                                HttpResponse response = client.execute(get);
                                String result = EntityUtils.toString(response.getEntity());
                                Map<String, Object> map = JSONUtil.toBean(result, Map.class);
                                if (!Objects.equals(map.get("code"), 200)) {
                                    System.out.println("result:" + result);
                                }
                            } catch (ConnectTimeoutException e) {
                                System.err.println("连接超时: " + e.getMessage());
                            } catch (SocketTimeoutException e) {
                                System.err.println("请求超时: " + e.getMessage());
                            } catch (IOException e) {
                                System.err.println("IO异常: " + e.getMessage());
                            }
                            return false;
                        });
            });
        }
        await().atMost(Duration.ofHours(2))
                .until(b::get);
    }


}
